
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @description： 封装工具类
 * @Author MRyan
 * @Date 2020/11/3 14:30
 * @Version 1.0
 */
public class RabbitMqUtil {

    private static volatile ConnectionFactory connectionFactory = null;
    private static Connection connection = null;

    private RabbitMqUtil() {
    }

    public static Connection getConnection(String host, int port, String virtualhost, String username, String password) {
        if (connectionFactory == null) {
            synchronized (RabbitMqUtil.class) {
                if (connectionFactory == null) {
                    //创建连接mq的连接工厂对象
                    connectionFactory = new ConnectionFactory();
                    //设置连接rabbitmq的主机
                    connectionFactory.setHost(host);
                    //设置端口号
                    connectionFactory.setPort(port);
                    //设置连接哪个虚拟主机
                    connectionFactory.setVirtualHost(virtualhost);
                    //访问虚拟主机的用户名和密码
                    connectionFactory.setUsername(username);
                    connectionFactory.setPassword(password);
                    // 获取连接对象
                    try {
                        connection = connectionFactory.newConnection();
                    } catch (IOException | TimeoutException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return connection;
    }


    public static void close(Connection connection, Channel channel) throws IOException, TimeoutException {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }


}
